var user = require('../models/user')
mongoose.Promise = global.Promise;
var User = mongoose.model('User')
var Path = require('path')
var _ = require('underscore')
var fs = require('fs')
var config = require('../../config');
var wechatApi = config.getWechat();
// signup
exports.showSignup = function *(next) {
  yield this.render('pages/signup', {
    title: '注册页面'
  })
}

exports.showSignin = function* (next) {
  yield this.render('pages/signin', {
    title: '登录页面'
  })
}

exports.signup = function *(next) {
  var _user = this.request.body.user

  var user = yield User.findOne({name: _user.name}).exec()
  if (user) {
    this.redirect('/signin')
    return next
  }
  else {
    user = new User(_user)
    yield user.save()
    this.session.user = user
    this.redirect('/')
  }
}

// signin
exports.signin = function *(next) {
  var _user = this.request.body.user
  var name = _user.name
  var password = _user.password

  var user = yield User.findOne({name: name}).exec()

  if (!user) {
    this.redirect('/signup')
    return next
  }
  var isMatch = yield user.comparePassword(password,user.password)
  if (isMatch) {
    this.session.user = user
    this.redirect('/')
  }
  else {
    this.redirect('/signin')
  }
}

// logout
exports.logout =  function *(next) {
  delete this.session.user
  //delete app.locals.user

  this.redirect('/')
}

// userlist page
exports.list = function *(next) {
  var users = yield User.fetch()
  console.log(users)
  yield this.render('pages/userlist', {
    title: 'imooc 用户列表页',
    users: users
  })
}

// midware for user
exports.signinRequired = function *(next) {
  var user = this.session.user

  if (!user) {
    this.redirect('/signin')
  }else{
     yield next
  }

  
}

exports.adminRequired = function *(next) {
  var user = this.session.user

  if (user.role <= 10) {
    this.redirect('/signin')
  }else{
    yield next
  }
}

exports.update = function *(next){
  var body = this.request.body
  var file = body.files.photopath
  var exobj = {name: body.fields.name}
  if(file){
    var filePath = file.path
    var name = file.name

    var fname = filePath.replace("public\\upload\\", "").replace("public/upload/", "");
    var newPath = Path.join(__dirname, '../../', '/public/upload/' + fname)
    var res = yield wechatApi.uploadAliOss(name,newPath)
    fs.unlink(newPath)
    exobj.path = res.url
  }

  var user = yield User.findOne({_id: body.fields.id}).exec()
  user = _.extend(user,exobj)
  console.log(user)
  yield user.save()
  this.body = {
    success: true
  }
}